<template>
	<!-- 头部搜索条件 -->
	<a-card :bordered="false" class="mb-3">
		<!-- <a-breadcrumb separator=">" class="mb-4 pl-[10px]">
			<a-breadcrumb-item>客资管理</a-breadcrumb-item>
			<a-breadcrumb-item><a href="">客户公海</a></a-breadcrumb-item>
		</a-breadcrumb> -->

		<a-tabs v-model:activeKey="activeKey" @change="onTableTypeChange">
			<a-tab-pane :key="0" tab="全部公海"></a-tab-pane>
			<a-tab-pane :key="1" tab="我管理的"></a-tab-pane>
		</a-tabs>

		<a-form ref="searchFormRef" name="advanced_search" :model="searchFormState" class="ant-advanced-search-form">
			<div class="flex justify-between items-center">
				<a-space :size="16">
					<a-input-group compact>
						<a-select v-model:value="searchFormState.searchType" style="width: 100px" @change="onSearchType">
							<a-select-option :value="0">线索名称</a-select-option>
							<a-select-option :value="1">联系方式</a-select-option>
							<a-select-option :value="2">前跟进人</a-select-option>
						</a-select>
						<a-input
							v-model:value="searchTextComputed"
							style="width: 200px"
							placeholder="请输入关键字搜索"
							allowClear
							@pressEnter="table.clearRefreshSelected(true)"
						></a-input>
					</a-input-group>
					<a-select
						v-model:value="searchFormState.highSeasId"
						:options="highSeasOptions"
						:field-names="fieldNames"
						placeholder="请选择公海"
						class="w-[200px]"
					></a-select>
					<a-select
						v-model:value="searchFormState.levelId"
						:options="levelOptions"
						:field-names="fieldNames"
						mode="multiple"
						placeholder="请选择等级"
						class="w-[170px]"
						allowClear
					></a-select>
					<a-button type="primary" @click="onSearchSubmit">查询</a-button>
					<a-button @click="filterVisible = true">更多筛选</a-button>
				</a-space>
				<a-button v-if="hasPerm('bizCluePoolAdd')" type="primary" @click="newCustomerVisible = true">新增线索</a-button>
			</div>
		</a-form>
	</a-card>
	<!--	class="h-full"-->
	<a-card>
		<a-space :size="16" class="mb-6">
			<template v-if="hasPerm('bizCluePoolBatchAction')">
				<span>批量操作</span>
				<a-select v-model:value="batchType" style="width: 100px" @change="onBatchTypeChange">
					<a-select-option :value="1">批量领取</a-select-option>
					<a-select-option :value="2">批量分配</a-select-option>
					<a-select-option :value="3">批量转移</a-select-option>
					<a-select-option :value="4">批量删除</a-select-option>
				</a-select>
				<a-button :disabled="!selectedRowKeys.length" type="primary" @click="onBatchAction">确定</a-button>
			</template>
			<a-button v-if="hasPerm('bizCluePoolImport')" type="primary" @click="importVisible = true">导入线索</a-button>
			<a-button v-if="hasPerm('bizCluePoolExport')" type="primary" @click="onExportSubmit">导出线索</a-button>
		</a-space>
		<s-table
			ref="table"
			:columns="columns"
			:data="loadData"
			:page-num="pageNum"
			:size="pageSize"
			bordered
			:row-key="(record) => record.id"
			:tool-config="toolConfig"
			:row-selection="options.rowSelection"
			:scroll="{ x: 1200 }"
		>
			<template #bodyCell="{ text, column, record }">
				<template v-if="column.dataIndex === 'customerName'">
					<a-space>
						<div class="truncate w-[280px]" :title="text">
							<a v-if="hasPerm('bizCluePoolView')" @click="onDetail(record.id)">{{ text }}</a>
							<span v-else>{{ text }}</span>
						</div>
						<a-tag v-if="record.customerType === 1" color="#108ee9">企业</a-tag>
						<a-tag v-if="record.customerType === 2" color="#108ee9">自然人</a-tag>
					</a-space>
				</template>
				<template v-if="column.dataIndex === 'contactNum'">
					<a-popover v-if="record.contactNum" trigger="click" placement="left">
						<template #content>
							<a-spin :spinning="spinning">
								<div ref="scollBox" class="max-h-[280px] overflow-y-auto p-3" @scroll="scollMore">
									<div v-for="item in showPersons" :key="item.id" class="flex justify-between my-1">
										<div class="mr-2">{{ item.contactsName || '---' }}</div>
										<div>
											手机：
											<a
												@click="
													callPhone(
														item.id,
														record.customerCode,
														item.contactsPhone,
														record.customerName,
														record.followUpStatus,
														record
													)
												"
											>
												<PhoneFilled style="transform: rotateY(180deg)" />{{
													record.phoneEncryptFlag === 'true'
														? $TOOL.desensitizePhone(item.contactsPhone)
														: item.contactsPhone
												}}
											</a>
										</div>
									</div>
									<div class="text-center">
										<a-spin :spinning="loadingSpinning" size="small" class="mb-[10px]" />
									</div>
								</div>
							</a-spin>
						</template>
						<a @click.stop="getPersons(record.customerCode)">
							<PhoneFilled style="transform: rotateY(180deg)" />
							{{ record.contactNum }}条
						</a>
					</a-popover>
					<span v-else />
				</template>
				<template v-if="column.dataIndex === 'labelNames'">
					<tag-list-space v-if="record.labelNames" :list="record.labelNames?.split(',')" :show-num="2" />
					<span v-else>-</span>
				</template>
				<template v-if="column.dataIndex === 'recordType'">
					{{ $TOOL.dictTypeData('CUSTOMER_RECORD_TYPE', record.recordType) }}
				</template>
				<template v-if="column.dataIndex === 'followUpStatus'">
					{{ ['未跟进', '跟进中', '已转换'][record.followUpStatus] }}
				</template>
				<template v-if="column.dataIndex === 'action'">
					<a-button
						v-if="
							hasPerm('bizCluePoolReceive') &&
							[ResourceAllocationRuleEnum.EMPLOYEE_COLLECTION, ResourceAllocationRuleEnum.EMPLOYEE_AND_ADMIN].includes(
								record.allocateFlag
							) &&
							record.memberFlag === CommonDetermineEnum.YES
						"
						type="link"
						@click="onReceive([{ id: record.id }])"
						>领取</a-button
					>
					<a-button
						v-if="
							hasPerm('bizCluePoolAllocate') &&
							[ResourceAllocationRuleEnum.ADMIN_ALLOCATION, ResourceAllocationRuleEnum.EMPLOYEE_AND_ADMIN].includes(
								record.allocateFlag
							) &&
							record.adminFlag === CommonDetermineEnum.YES
						"
						type="link"
						@click="onAllocate([{ id: record.id }])"
						>分配</a-button
					>
				</template>
			</template>
		</s-table>
	</a-card>
	<!-- 更多筛选条件 -->
	<a-modal v-model:visible="filterVisible" title="更多筛选" :footer="null" :width="500" @cancel="onFilterCancel">
		<a-form ref="filterSearchFormRef" :model="searchFormState" :label-col="{ style: { width: '100px' } }">
			<a-form-item label="线索类型" name="clueType">
				<a-select placeholder="请选择线索类型" v-model:value="searchFormState.clueType" allowClear>
					<a-select-option value="新线索">新线索</a-select-option>
					<a-select-option value="旧线索">旧线索</a-select-option>
				</a-select>
			</a-form-item>
			<a-form-item label="标签">
				<select-tag-popover v-model:value="searchFormState.labelList" simple :type="1" />
			</a-form-item>
			<a-form-item label="线索来源" name="sourceId">
				<a-select
					v-model:value="searchFormState.sourceId"
					:options="sourceOptions"
					:fieldNames="fieldNames"
					placeholder="请选择线索来源"
					allowClear
				></a-select>
			</a-form-item>
			<a-form-item label="录入方式" name="recordType">
				<a-select
					v-model:value="searchFormState.recordType"
					:options="recordTypeOptions"
					placeholder="请选择录入方式"
					allowClear
				></a-select>
			</a-form-item>
			<a-form-item label="所属行业" name="industryId">
				<a-select
					v-model:value="searchFormState.industryId"
					:options="industryOptions"
					:fieldNames="industryFieldNames"
					placeholder="请选择所属行业"
					allowClear
				></a-select>
			</a-form-item>
			<a-form-item label="所属地区" name="districtIdArr">
				<a-cascader
					v-model:value="searchFormState.districtIdArr"
					:options="areaOptions"
					:fieldNames="fieldNames"
					placeholder="请选择所属地区"
					allowClear
				></a-cascader>
			</a-form-item>
			<a-form-item label="注册日期" name="regTime">
				<a-range-picker
					valueFormat="YYYY-MM-DD"
					v-model:value="searchFormState.regTime"
					allowClear
					style="width: 100%"
				/>
			</a-form-item>
			<!--			<a-form-item label="呼叫状态" name="callState">-->
			<!--				<a-select-->
			<!--					v-model:value="searchFormState.callState"-->
			<!--					:options="callStatusOptions"-->
			<!--					placeholder="请选择呼叫状态"-->
			<!--					allowClear-->
			<!--				></a-select>-->
			<!--			</a-form-item>-->
			<a-form-item label="创建线索时间" name="createDate">
				<a-range-picker
					v-model:value="searchFormState.createDate"
					show-date
					valueFormat="YYYY-MM-DD"
					allowClear
					style="width: 100%"
				/>
			</a-form-item>
			<a-form-item label="最近跟进时间" name="lastFollowDate">
				<a-range-picker
					v-model:value="searchFormState.lastFollowDate"
					show-date
					valueFormat="YYYY-MM-DD"
					allowClear
					style="width: 100%"
				/>
			</a-form-item>
			<a-form-item label="掉保时间" name="dropDate">
				<a-range-picker
					v-model:value="searchFormState.dropDate"
					show-date
					valueFormat="YYYY-MM-DD"
					allowClear
					style="width: 100%"
				/>
			</a-form-item>
		</a-form>
		<div class="flex justify-between items-center mt-[40px]">
			<a-button type="link" @click="onFilterReset">清空筛选</a-button>
			<a-space>
				<a-button type="primary" @click="onFilterSubmit">筛选</a-button>
				<a-button @click="onFilterCancel">取消</a-button>
			</a-space>
		</div>
	</a-modal>
	<!-- 新增客户 -->
	<clue-modal
		v-if="newCustomerVisible"
		type="new"
		:callBack="addCallBack"
		v-model:visible="newCustomerVisible"
		@finished="table.clearRefreshSelected(true)"
	/>
	<!-- 分配客户 -->
	<allocate-modal ref="allocateFormRef" :high-seas-id="searchFormState.highSeasId" @successful="operateDone" />
	<!-- 转移客户 -->
	<transfer-modal ref="transferFormRef" @successful="operateDone" />
	<!-- 删除客户 -->
	<delete-modal ref="deleteFormRef" @successful="operateDone" />
	<!-- 导入客户 -->
	<a-modal v-model:visible="importVisible" title="导入线索" :footer="false" :width="600" @cancel="onImportCancel">
		<div class="px-6">
			<div class="flex items-center gap-2 bg-gray-200 mb-5 p-2">
				<ExclamationCircleFilled style="font-size: 18px; color: #6e6e6e" />
				<div>可选择自己作为管理员的公海进行数据导入</div>
			</div>
			<a-form
				ref="importFormRef"
				:model="importFormData"
				:rules="importFormRules"
				:label-col="{ style: { width: '100px' } }"
			>
				<a-form-item label="目标公海" name="highSeasId">
					<a-select
						v-model:value="importFormData.highSeasId"
						:options="highSeasOptions"
						:fieldNames="fieldNames"
						placeholder="请选择公海"
					></a-select>
				</a-form-item>
				<a-form-item label="上传文件" name="url">
					<xn-upload ref="fileUploadRef" uploadMode="drag" :before-upload="beforeUpload" @uploadDone="onUploadDone">
						<template #title> 将文件拖拽至此处，或<a-button type="link" class="pl-0">点击上传</a-button></template>
					</xn-upload>
					<h4 class="mt-4">温馨提示</h4>
					<ul class="mb-0 pl-8">
						<li>文件必须是xlsx格式</li>
						<li>字段前加红色"*"为必填字段</li>
						<li>单次最多导入前3000条客户数据</li>
						<li>文件大小限制2Mb</li>
						<li><a-button type="link" class="pl-0 pt-0" @click="onTemplateDownload">点击下载模板</a-button></li>
					</ul>
				</a-form-item>
			</a-form>
		</div>
		<div class="flex items-center justify-between">
			<div></div>
			<a-space>
				<a-button type="primary" :loading="submitLoading" @click="onImportSubmit">确定</a-button>
				<a-button @click="onImportCancel">取消</a-button>
			</a-space>
		</div>
	</a-modal>
	<!-- 导入客户成功 -->
	<a-modal
		v-model:visible="importResultVisible"
		title="导入线索"
		:footer="false"
		:width="600"
		@cancel="onImportResultCancel"
	>
		<div v-if="importResultData.type" class="flex flex-col p-4 text-center">
			<check-circle-filled :style="{ fontSize: '50px', color: 'dodgerblue' }" />
			<h3 class="mt-4">导入成功</h3>
			<div class="mt-8">
				本次导入线索数据 <span class="text-blue-500">{{ importResultData.totalCount }}</span> 条，成功
				<span class="text-blue-500">{{ importResultData.successCount }}</span> 条，失败
				<span :class="importResultData.errorCount ? 'text-red-500' : 'text-blue-500'">{{
					importResultData.errorCount
				}}</span>
				条
				<template v-if="importResultData.errorCount"
					>，<a-button type="link" class="p-0" @click="onPreviewErrorDetail">查看失败原因</a-button></template
				>
			</div>
		</div>
		<div v-else class="flex flex-col p-4 text-center">
			<close-circle-filled :style="{ fontSize: '50px', color: 'red' }" />
			<h3 class="mt-4">导入失败</h3>
			<div class="text-gray-400">{{ importResultData.msg }}</div>
		</div>
	</a-modal>
	<!-- 导入查看失败原因 -->
	<a-modal
		v-model:visible="importErrorReasonVisible"
		title="查看失败原因"
		:footer="false"
		:width="800"
		@cancel="onImportErrorReasonCancel"
	>
		<a-table :dataSource="importResultData.errorDetail" :columns="impErrorColumns" size="small" />
	</a-modal>
</template>
<script setup>
	import clueModal from '../clueManagement/clueModal.vue'
	import allocateModal from './modal/allocateModal.vue'
	import transferModal from './modal/transferModal.vue'
	import deleteModal from './modal/deleteModal.vue'
	import { message, Upload } from 'ant-design-vue'
	import highSeasClueApi from '@/api/biz/highSeasClueApi'
	import { required } from '@/utils/formRules'
	import clueHighSeasApi from '@/api/biz/crm/clueHighSeasApi'
	import customerLevelApi from '@/api/biz/crm/customerLevelApi'
	import customerSourceApi from '@/api/biz/crm/customerSourceApi'
	import tool from '@/utils/tool'
	import erpCustomerApi from '@/api/erp/erpCustomerApi'
	import erpSystemApi from '@/api/erp/erpSystemApi'
	import { CommonDetermineEnum, ResourceAllocationRuleEnum } from '@/utils/enum'
	import downloadUtil from '@/utils/downloadUtil'
	import customerApi from '@/api/biz/customerApi'
	import { useRouter } from 'vue-router'
	import useTableCache from '@/hook/useTableCache'
	import useTableFilter from '@/hook/useTableFilter'
	import { globalStore } from '@/store'

	const store = globalStore()

	const router = useRouter()
	const tableCache = useTableCache('highSeasClue', ['bizHighSeasClue', 'bizHighSeasClueDetail'])
	const tableFilter = useTableFilter('highSeasClueFilter', 'bizHighSeasClueDetail')

	onBeforeMount(() => {
		const tableCacheData = tableCache.get()
		if (tableCacheData) {
			Object.assign(searchFormState, tableCacheData.searchFormState)
			activeKey.value = tableCacheData.activeKey
			pageNum.value = tableCacheData.pageNum
			pageSize.value = tableCacheData.pageSize
		}
	})

	/**
	 * ====================
	 *       基本逻辑
	 * ====================
	 */
	const submitLoading = ref(false)
	const fieldNames = {
		label: 'name',
		value: 'id'
	}

	const tempHighSeasId = ref()

	const columns = [
		{
			title: '线索名称',
			dataIndex: 'customerName',
			width: 360,
			align: 'center',
			ellipsis: true
		},
		{
			title: '联系方式',
			dataIndex: 'contactNum',
			width: 200,
			align: 'center',
			ellipsis: true
		},
		{
			title: '标签',
			dataIndex: 'labelNames',
			width: 320,
			align: 'center',
			ellipsis: true
		},
		{
			title: '所属地区',
			dataIndex: 'district',
			width: 150,
			align: 'center',
			ellipsis: true
		},
		{
			title: '注册日期',
			dataIndex: 'regTime',
			width: 150,
			align: 'center',
			ellipsis: true
		},
		{
			title: '线索地址',
			dataIndex: 'customerAddress',
			width: 280,
			align: 'center',
			ellipsis: true
		},
		{
			title: '线索类型',
			dataIndex: 'clueType',
			width: 100,
			align: 'center',
			ellipsis: true
		},
		{
			title: '创建人',
			dataIndex: 'createUserName',
			width: 100,
			align: 'center'
		},
		{
			title: '线索来源',
			dataIndex: 'customerFrom',
			width: 150,
			align: 'center',
			ellipsis: true
		},
		{
			title: '录入方式',
			dataIndex: 'recordType',
			width: 100,
			align: 'center'
		},
		{
			title: '所属公海',
			dataIndex: 'highSeasName',
			width: 240,
			align: 'center',
			ellipsis: true
		},
		{
			title: '线索创建时间',
			dataIndex: 'createAt',
			width: 150,
			align: 'center'
		},
		{
			title: '线索掉保时间',
			dataIndex: 'dropTime',
			width: 150,
			align: 'center'
		},
		{
			title: '最近跟进时间',
			dataIndex: 'lastFollowTime',
			width: 150,
			align: 'center'
		},
		{
			title: '前跟进人',
			dataIndex: 'lastFollowUserName',
			width: 150,
			align: 'center',
			ellipsis: true
		}
	]
	// if (hasPerm('bizDictEdit')) {
	columns.push({
		title: '操作',
		dataIndex: 'action',
		align: 'center',
		width: '150px',
		fixed: 'right'
	})
	// }
	const toolConfig = { refresh: true, height: true, columnSetting: true, striped: false }
	const table = ref(null)
	const pageNum = ref(1)
	const pageSize = ref(10)

	/**
	 * 点击联系人条数获取联系人列表
	 */
	const spinning = ref(false)
	const loadingSpinning = ref(false)
	const showPersons = ref([])
	const personSize = ref(30)
	const getPersonCode = ref('')
	const personTotal = ref(0)
	const getPersons = (code) => {
		if (code) {
			showPersons.value = []
			spinning.value = true
		} else {
			loadingSpinning.value = true
		}

		const getSize = code ? 30 : personSize.value
		const params = {
			customerCode: code ?? getPersonCode.value,
			current: 1,
			size: getSize
		}
		customerApi
			.getPersonList(params)
			.then((res) => {
				spinning.value = false
				loadingSpinning.value = false

				showPersons.value = res.records
				personTotal.value = res.total
				if (code) {
					getPersonCode.value = code
				}
			})
			.catch(() => {
				spinning.value = false
				loadingSpinning.value = false
			})
	}
	const scollBox = ref(null)
	const scollMore = () => {
		if (showPersons.value.length >= personTotal.value) {
			return
		}
		const onBottom = Math.ceil(scollBox.value.scrollTop + scollBox.value.offsetHeight) >= scollBox.value.scrollHeight
		if (onBottom) {
			personSize.value += 10
			getPersons()
		}
	}

	/**
	 * 获取客户列表数据
	 */
	const loadData = async (parameter) => {
		tempHighSeasId.value = searchFormState.highSeasId
		const { searchType, keyword } = searchFormState
		if (keyword) {
			const typeKeyList = ['customerName', 'phone', 'lastFollowUserName']
			searchFormState[typeKeyList[searchType]] = keyword
		} else {
			onSearchType()
		}

		parameter.type = activeKey.value
		const searchFormParam = JSON.parse(JSON.stringify(searchFormState))
		// createDate范围查询条件重载
		if (searchFormParam.createDate) {
			searchFormParam.startCreateDate = searchFormParam.createDate[0]
			searchFormParam.endCreateDate = searchFormParam.createDate[1]
			delete searchFormParam.createDate
		}
		// lastFollowDate范围查询条件重载
		if (searchFormParam.lastFollowDate) {
			searchFormParam.startLstFollowDate = searchFormParam.lastFollowDate[0]
			searchFormParam.endLstFollowDate = searchFormParam.lastFollowDate[1]
			delete searchFormParam.lastFollowDate
		}
		// dropDate范围查询条件重载
		if (searchFormParam.dropDate) {
			searchFormParam.startDropDate = searchFormParam.dropDate[0]
			searchFormParam.endDropDate = searchFormParam.dropDate[1]
			delete searchFormParam.dropDate
		}

		// dropDate范围查询条件重载
		if (searchFormParam.regTime) {
			searchFormParam.startRegDate = searchFormParam.regTime[0]
			searchFormParam.endRegDate = searchFormParam.regTime[1]
			delete searchFormParam.regTime
		}

		if (searchFormParam.levelId.length) {
			searchFormParam.levelId = searchFormParam.levelId.join(',')
		} else {
			delete searchFormParam.levelId
		}
		if (searchFormParam.labelList.length) {
			searchFormParam.labelList = searchFormParam.labelList.join(',')
		} else {
			delete searchFormParam.labelList
		}
		delete searchFormParam.searchType
		delete searchFormParam.districtIdArr
		// if (!searchFormParam.highSeasId) return

		Object.assign(parameter, searchFormParam)
		tableFilter.set(parameter)
		return highSeasClueApi.page(parameter).then((data) => {
			return data
		})
	}

	const activeKey = ref(0)
	const onTableTypeChange = (value) => {
		Object.assign(searchFormState, {
			searchType: 0,
			keyword: null,
			customerName: null,
			phone: null,
			lastFollowUserName: null,
			levelId: []
		})
		table.value.clearRefreshSelected(true)
	}

	onMounted(() => {
		highSeasList()
		levelList()
		sourceList()
		industryList()
		areaList()
	})

	/**
	 * 公海列表
	 */
	const highSeasOptions = ref([])
	const highSeasList = () => {
		clueHighSeasApi.list().then((data) => {
			if (hasPerm('bizCluePoolAll')) {
				data.push({ id: '', name: '全部公海' })
			}

			highSeasOptions.value = data
			if (data.length && !searchFormState.highSeasId) {
				const defaultHighSeasId = data[0].id
				searchFormState.highSeasId = defaultHighSeasId
				tempHighSeasId.value = defaultHighSeasId
				table.value.refresh(true)
			}
		})
	}

	/**
	 * 客户等级
	 */
	const levelOptions = ref([])
	const levelList = () => {
		customerLevelApi.list().then((data) => {
			levelOptions.value = data
		})
	}

	/**
	 * 客户来源
	 */
	const sourceOptions = ref([])
	const sourceList = () => {
		customerSourceApi.list().then((data) => {
			sourceOptions.value = data
		})
	}

	/**
	 * 录入方式
	 */
	const recordTypeOptions = tool.dictList('CUSTOMER_RECORD_TYPE')

	/**
	 * 所属行业
	 */
	const industryFieldNames = {
		label: 'typeValue',
		value: 'id'
	}
	const industryOptions = ref([])
	const industryList = () => {
		erpCustomerApi.industryList().then((data) => {
			industryOptions.value = data
		})
	}

	/**
	 * 所属地区
	 */
	const areaOptions = ref([])
	const areaList = () => {
		erpSystemApi.areaTree().then((data) => {
			areaOptions.value = data
		})
	}

	/**
	 * 呼叫状态
	 */
	// const callStatusOptions = tool.dictList('OUTBOUND_RESULT')
	const callStatusOptions = [
		{ label: '已接通', value: 1 },
		{ label: '未接通', value: 0 }
	]

	/**
	 * 拨号
	 * @param {*} code customercode
	 * @param {*} id 联系人记录id
	 * @param {*} phone 手机号
	 * @param {*} name 姓名
	 * @param {*} status 状态
	 * @param record
	 */
	const callPhone = (id, code, phone, name, status, record) => {
		store.dashboardNode?.open({ id, code, phone, name, type: 5, status })
		nextTick(() => {
			store.tagIdList = record.labelIds ? record.labelIds.split(',') : []
			store.tagNameList = record.labelNames ? record.labelNames.split(',') : []
		})
	}

	/**
	 * 基础查询
	 */
	const searchFormRef = ref()
	let searchFormState = reactive({
		clueType: null,
		searchType: 0,
		keyword: null,
		customerName: null,
		phone: null,
		lastFollowUserName: null,
		highSeasId: '',
		levelId: [],
		sourceId: null,
		recordType: null,
		industryId: null,
		districtIdArr: [],
		regTime: [],
		callState: null,
		createDate: [],
		lastFollowDate: [],
		dropDate: [],
		labelList: []
	})
	const searchTextComputed = computed({
		get() {
			return searchFormState.keyword
		},
		set(val) {
			searchFormState.keyword = val.replace(/(^\s*)|(\s*$)/g, '')
		}
	})
	const onSearchType = (value) => {
		Object.assign(searchFormState, {
			keyword: null,
			customerName: null,
			phone: null,
			lastFollowUserName: null
		})
	}

	/**
	 * 更多筛选
	 */
	const filterSearchFormRef = ref()
	const filterVisible = ref(false)

	const onSearchSubmit = () => {
		table.value.clearRefreshSelected(true)
	}
	const onFilterReset = () => {
		filterSearchFormRef.value.resetFields()
		searchFormState.labelList = []
		table.value.refresh(true)
	}
	const onFilterSubmit = () => {
		tempHighSeasId.value = searchFormState.highSeasId
		const { districtIdArr } = searchFormState
		searchFormState.districtId = districtIdArr && districtIdArr.length ? districtIdArr.join(',') : null
		table.value.clearRefreshSelected(true)
		filterVisible.value = false
	}
	const onFilterCancel = () => {
		filterVisible.value = false
	}

	/**
	 * 新增客户
	 */
	const newCustomerVisible = ref(false)
	const addCallBack = ({ contactPerson, contactPhone, ...other }) =>
		highSeasClueApi.submitForm({
			realName: contactPerson,
			phone: contactPhone,
			...other
		})

	/**
	 * 批量操作
	 */
	const batchType = ref(1)
	const selectedRowKeys = ref([])
	// 列表选择配置
	const options = {
		rowSelection: {
			onChange: (selectedRowKey, selectedRows) => {
				selectedRowKeys.value = selectedRowKey
			},
			getCheckboxProps: (record) => {
				const unDisabled =
					(batchType.value === 1 &&
						[ResourceAllocationRuleEnum.EMPLOYEE_COLLECTION, ResourceAllocationRuleEnum.EMPLOYEE_AND_ADMIN].includes(
							record.allocateFlag
						) &&
						record.memberFlag === CommonDetermineEnum.YES) ||
					(batchType.value === 2 &&
						[ResourceAllocationRuleEnum.ADMIN_ALLOCATION, ResourceAllocationRuleEnum.EMPLOYEE_AND_ADMIN].includes(
							record.allocateFlag
						) &&
						record.adminFlag === CommonDetermineEnum.YES) ||
					batchType.value === 3 ||
					batchType.value === 4
				return {
					disabled: !unDisabled
				}
			}
		}
	}
	const onBatchTypeChange = () => {
		table.value.clearSelected()
	}
	const onBatchAction = () => {
		if (!selectedRowKeys.value.length) {
			return message.warning('请至少选中一项记录')
		}

		const list = selectedRowKeys.value.map((id) => ({ id }))
		if (batchType.value === 1) {
			// 批量领取
			onReceive(list, table)
		} else if (batchType.value === 2) {
			// 批量分配
			onAllocate(list)
		} else if (batchType.value === 3) {
			// 批量转移
			onTransfer(list)
		} else if (batchType.value === 4) {
			// 批量删除
			onDelete(list)
		}
	}

	/**
	 * 详情
	 */
	const onDetail = (id) => {
		tool.limitClick(() => {
			const { localPagination } = table.value
			tableCache.set({
				searchFormState: searchFormState,
				activeKey: activeKey.value,
				pageNum: localPagination.current,
				pageSize: localPagination.pageSize
			})
			router.push(`/biz/highSeasClue/detail?id=${id}`)
		})
	}

	/**
	 * 领取客户
	 */
	const onReceive = (list) => {
		allocateFormRef.value.receiveAction(list, () => {
			table.value.clearRefreshSelected(true)
		})
	}

	/**
	 * 分配客户
	 */
	const allocateFormRef = ref()
	const onAllocate = (list) => {
		allocateFormRef.value.onOpen(list)
	}
	const operateDone = () => {
		table.value.clearRefreshSelected(true)
	}
	/**
	 * 转移客户
	 */
	const transferFormRef = ref()
	const onTransfer = (list) => {
		transferFormRef.value.onOpen(list)
	}

	/**
	 * 删除客户
	 */
	const deleteFormRef = ref()
	const onDelete = (list) => {
		deleteFormRef.value.onOpen(list)
	}

	/**
	 * 导入客户
	 */
	const importFormRef = ref()
	const fileUploadRef = ref()
	let importVisible = ref(false)
	const importFormData = ref({})
	const importFormRules = {
		highSeasId: [required('请选择公海')],
		url: [required('请上传文件')]
	}
	const onImportSubmit = () => {
		importFormRef.value.validate().then(() => {
			submitLoading.value = true
			highSeasClueApi
				.importData(importFormData.value)
				.then((data) => {
					onImportCancel()
					Object.assign(importResultData, data)
					importResultVisible.value = true
					table.value.clearRefreshSelected(true)
				})
				.finally(() => {
					submitLoading.value = false
				})
		})
	}
	const onImportCancel = () => {
		importFormRef.value.resetFields()
		importVisible.value = false
		fileUploadRef.value.resetFileList([])
	}

	/**
	 * 导入结果
	 */
	const importResultVisible = ref(false)
	const importResultData = reactive({
		type: 1, // 0-失败 1-成功
		msg: null,
		totalCount: 0,
		successCount: 0,
		errorCount: 0,
		errorDetail: []
	})
	const onImportResultCancel = () => {
		importResultVisible.value = false
	}
	const onPreviewErrorDetail = () => {
		importErrorReasonVisible.value = true
	}

	/**
	 * 查看导入失败原因
	 */
	const importErrorReasonVisible = ref(false)
	const impErrorColumns = [
		// {
		// 	title: '索引',
		// 	dataIndex: 'index',
		// 	width: '80px'
		// },
		// {
		// 	title: '行号',
		// 	dataIndex: 'lineNumber',
		// 	width: '80px'
		// },
		// {
		// 	title: '线索名称',
		// 	dataIndex: 'customerName',
		// 	width: '200px'
		// },
		{
			title: '行号',
			dataIndex: 'index',
			width: '80px'
		},
		{
			title: '原因',
			dataIndex: 'msg',
			ellipsis: true
		}
	]
	const onImportErrorReasonCancel = () => {
		importErrorReasonVisible.value = false
	}

	/**
	 * 导出客户
	 */
	const onExportSubmit = () => {
		highSeasClueApi
			.exportData({
				highSeasId: tempHighSeasId.value,
				poolIdParamList: selectedRowKeys.value.map((id) => ({ id }))
			})
			.then((res) => {
				downloadUtil.resultDownload(res)
			})
	}

	/**
	 * 模板下载
	 */
	const onTemplateDownload = () => {
		highSeasClueApi.downloadImportPoolTemplate().then((res) => {
			downloadUtil.resultDownload(res)
		})
	}
	/**
	 * 模板上传
	 */
	const beforeUpload = (file) => {
		const isXlsx = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
		if (!isXlsx) {
			message.error('文件必须是xlsx格式!')
		}
		const isLt2M = file.size / 1024 / 1024 < 2
		if (!isLt2M) {
			message.error('文件大小限制2Mb!')
		}
		const status = isXlsx && isLt2M
		if (!status) {
			return Upload.LIST_IGNORE
		}
		return status
	}
	const onUploadDone = (result) => {
		importFormData.value.url = result.length ? result[0].url : null
	}
</script>
<style lang="less" scoped>
	// :deep(.ant-table) {
	// 	min-height: calc(100vh - 480px);
	// }
</style>
